# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import time
from collections import OrderedDict

import requests
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from django.conf import settings
from django.utils.encoding import smart_unicode

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError, KspayError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://api.363pay.com/payment/pay2'
_QUERY_GATEWAY = 'https://web.363pay.com/api/v1/merchant/order'

APP_CONF = {
    'KS': {
        'API_KEY': '38620efead0cf268efb5d42ba07af7a11526465626',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+FsNWUoex+HLC2ILm1bH3hJSi
mZIX9cRYygh709itEzc7bgkEuvu1Zi/CVNMyjdhKd3yVRFtDdQKLSuVr/vuyxZda
lHeHQaKY/5WobN37HwKszsJ5GnEJ5d38R51UZuUS5jdEYSpxDHohZj4YTF633JFo
rp+qHOq25DPjkiABYQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDMus1PTaBQ2xxUF75Y0fOgz0weL5fVT7Q8IMN5EF1hYjysk6eV
ywggFF0VcLxbYZbtw0LaNgSmeEyQMhABG+BXOpeyh/ipGypkvzxRFfHRwo/z08bB
ik5txuXX0/DkZiQgjAC8VPFXk1GgP6a1OV56QEKltIgjIScciZ3KaS7IuQIDAQAB
AoGATpTI506RYVeo2PJAIpF7pNbMja2Q5tRwBsBAp0BLx2xQg6EtKwbCOKX4UJl0
AtNDfkF7cIxZXphAMvy0Pei4Q7LR5E3dXoIYd1ofLsy9DJwDg5AmD5WdQ5n/nyF3
s/+ZQIIPHrqU4DbR0V+kpS6ZCEH85HZ2EGqdgnt2+evi+QECQQDVezxwAOY/im6Q
N0AeZ5sFTzWfuV+Gbwa9FBdkPcpSlkaAVJck5Wf3L4XUKqbRs4RzXkY1r2Ajn01v
1etQejQhAkEA9YFX+46met+QEAkttRN58mfWNs3KRUf6aEyoJ0B+uQ78QdZz61N2
GcwbPU/RrUkr+MiV4y+FYfT5wzYaj8GBmQJBAKavcZI2cZEdYpTCPxM+bCEqJsGO
+RI7cHSD0nvXbzkq0uNyqQ0K/jFX7tOpddV4qKt36bQTOiq2QL1Yt0KAGGECQQCO
RnMSmczpEH6QjIEsmyjkzkBaalB6bgg0QZiBhuLppEGUdg+fpTKgKKTwlz1QS0Ns
XfJfQr7t0eacttIV1XKhAkAySJQ8DCMi3dSEyoapE62B+gMw1zv6QtRrm0VjDY9k
DEM1k0alYZR7+n+05TTsBouNd3O586GBDgAVH8i0B6me
-----END RSA PRIVATE KEY-----""",
    },
    'ZSQP': {
        'API_KEY': '90570ec3cecc01aff148cf3645604c431528972009',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC87XGldykW+NI+4YVKgnWFuL/D
l7igTqWtf8GRBstf7gfGinXV/0OxR3puYS1utUsyhnGYAueDQjoHee/XfHV5ViRq
bLLwyrbtFPijN8aaOXrC9NMYEu2xILmDVm51o887XEXVQm4RWs6zJHq+fF3NVj9Z
ObaTizQlKHdQvbG9uwIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDWcQHSP7sNb/RiaJDJSkspounDLBOzSPQDZnVVH68sqrJ6fggQ
pEFwPh6Ct6OoF8v4CMUc6fIKfvvVfjTrsc8nqsctx+ZyfjDvSc+7acEwwGZdmtWN
rSSKpm0yH5McRQrh3/fB0umeFjLdxZKp8L5kv7l5a2PIT+FS3WNPWnueLQIDAQAB
AoGAXgGoZL0fiSJ9Je7lGfkBvjz28WKPOFdQ8XSnFywOpSwnld9ONc1sCoKQ6YkL
q5LTDeb6UlSUkNleGRd8p56JSvLzxAk9nXBmgs8RXDFoIHO7T5PpplDWWMBJU/sB
LfhhvnP1XG8Kg9BHr3q1Cm7/ygPCZstllFCvNymclaJfbBkCQQDuSuCbnCN8oeuq
ffkF5N6KyFRFi0yVG8sga/1vHbxIoJX+StBGto0fS9+/oWKFASylaVBf1GAVKebd
rz+eZtmnAkEA5mBnE27V9w/+EN+1/2Hox/dcp1hiZay90ybJwoA8tEKZ9VoJTLHI
0U3ktrkdU7ttkfFCEVlE7GWf2dFm1e4cCwJAUnfVfeUunt6G6e1I9pI7tnoYOC06
ZsxEo0bcYc0/sT7qSiRoKmDZPECNAgv/RZqfceudplygmBJ1VLlm4hIkNwJBAKs8
ksE+DCpVJ8rRDg1icE1aTvNQXesnR/2QAj3hZb2zF47oOqtYJmV1GYC7/dGEKkBl
bG9KxFFWhEe6P07aatsCQQCiLDhLlGo5kKdLPIbGlIWPJnW8uyrBhA3+kG9x9lrf
HMvup6+y2jNLnt8qwSnmE9H8/5VCUka8fvn58TytXWk0
-----END RSA PRIVATE KEY-----""",
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['pub_key']


def _get_pri_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


def _gen_sign(message, key):
    key = RSA.importKey(key)
    h = SHA256.new(message)
    signer = Signature_pkcs1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)


def generate_sign(d, key, pri_key):
    '''  生成下单签名 '''
    s = 'bill_price={}&create_at={}&merchant_id={}&notify_url={}&order_id={}&payment={}{}'.format(
        d['bill_price'], d['create_at'], d['merchant_id'], d['notify_url'], d['order_id'], d['payment'], key
    )
    _LOGGER.info(u'newks2pay origin string: %s', s)
    return _gen_sign(s, pri_key)


def _verify_sign(data, signature, key):
    key = RSA.importKey(key)
    h = SHA256.new(data)
    verifier = Signature_pkcs1_v1_5.new(key)
    if verifier.verify(h, base64.b64decode(signature)):
        return True
    return False


def generate_rsa_sign_str(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s[0:len(s) - 1]
    s += key
    return s


def verify_notify_sign(params, key, pub_key):
    sign = params['sign']
    params.pop('sign')
    s = generate_rsa_sign_str(params, key)
    if _verify_sign(s.encode('utf8'), sign, pub_key) == False:
        _LOGGER.info("newks2pay sign not pass : %s", params)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型 [ wxpay, qqpay, alipay, unionpay jdpay ]
def _get_pay_type(type):
    if type == 'qq':
        return 'qqpay'
    elif type == 'alipay':
        return 'alipay'
    elif type == 'wxpay':
        return 'wxpay'
    elif type == 'jd':
        return 'jdpay'
    else:
        return 'unionpay'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/newks2pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("payment", _get_pay_type(service)),
        ("bill_price", '%.2f' % pay_amount),
        ("create_at", local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ("sign", ''),
        ("info", {
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "device_type": user_info.get('device_type') or 'android',
            "name": user_info.get('user_name') or '',
            "alipay_name": user_info.get('user_alicount') or '',
            "tel": user_info.get('tel') or '',
            "user_id": user_info.get('user_id') or '',
            "user_value": '100'
        })
    ))
    p_dict['notify_url'] = p_dict['notify_url'].replace('charge.xmrx05.com', '183.60.200.115')
    p_dict['info']['user_id'] = str(p_dict['info']['user_id'])
    p_dict['sign'] = generate_sign(p_dict, api_key, _get_pri_key(app_id))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    headers = {'Content-type': 'application/json'}
    _LOGGER.info('newks2pay brefore data: %s', p_data)
    response = requests.post(_GATEWAY, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('newks2pay rsp data: %s', response.text)
    res_obj = json.loads(response.text)
    flashid = res_obj.get('flashid')
    if flashid is not None:
        order_db.fill_third_id(pay.id, flashid)
    url = res_obj['qrcode']
    if 'https://qr.alipay.com/' in url:
        _LOGGER.info('newks2pay_qr_alipay_com')
        raise KspayError('newks2pay url qr_alipay_com')
    return {'charge_info': url}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("newks2pay notify body: %s", request.body)
    data = json.loads(smart_unicode(request.body))
    verify_notify_sign(data, api_key, _get_pub_key(app_id))
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('newks2pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data.get('flashid')
    total_fee = float(data['payed_money'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 10000:
        _LOGGER.info('newks2pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def generate_query_sign(d, key):
    s = '{}:{}:{}'.format(d['merchant_id'], d['time'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant_id', app_id),
        ('order_id', str(pay_id)),
        ('time', int(time.time())),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('newks2pay query : %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('newks2pay query rsp: %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        trade_status = data['status']
        trade_no = str(data['flashid'])
        total_fee = float(data['receipt_price'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == u'已付款':
            _LOGGER.info('newks2pay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('newks2pay data error, status_code: %s', response.status_code)
